package com.kevin.demo.utils;


import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.RichTextString;
import org.apache.poi.ss.usermodel.Workbook;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;


/**
 * Auth:baili
 * Date: 2018.05.16
 * @param <T> 应用泛型，代表任意一个符合javabean风格的类 注意这里为了简单起见，boolean型的属性xxx的get器方式为getXxx(),而不是isXxx()
 *
 */
public class ExcelExportUtil<T> {

    /**
     * 这是一个通用的方法，利用了JAVA的反射机制，可以将放置在JAVA集合中并且符合一定条件的数据以EXCEL 的形式输出到指定IO设备上
     * @param sheetName sheetName
     * @param dataset   需要导出的数据集合,集合中一定要放置符合javabean风格的类的对象。此方法支持的 javabean属性的数据类型有基本数据类型及String,Date
     * 日期格式为  "yyyy-MM-dd HH:mm:ss"
     * 产生两行表头：第一行中文，第二行英文字段名
     */
    @SuppressWarnings("unchecked")
    public HSSFWorkbook exportExcel(String sheetName, List<T> dataset, String[] comments) throws Exception {
        // 声明一个工作薄
        HSSFWorkbook workbook = new HSSFWorkbook();
        // 生成一个表格
        HSSFSheet sheet = workbook.createSheet(sheetName);
        // 设置表格默认列宽度为15个字节
        sheet.setDefaultColumnWidth((short) 15);
        // 生成一个样式
        HSSFCellStyle style = workbook.createCellStyle();
        // 设置这些样式
        style.setFillForegroundColor(HSSFColor.SKY_BLUE.index);
        style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        style.setBorderRight(HSSFCellStyle.BORDER_THIN);
        style.setBorderTop(HSSFCellStyle.BORDER_THIN);
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        // 生成一个字体
        HSSFFont font = workbook.createFont();
        font.setColor(HSSFColor.VIOLET.index);
        font.setFontHeightInPoints((short) 12);
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        // 把字体应用到当前的样式
        style.setFont(font);
        // 生成并设置另一个样式
        HSSFCellStyle style2 = workbook.createCellStyle();
        style2.setFillForegroundColor(HSSFColor.LIGHT_YELLOW.index);
        style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        style2.setBorderRight(HSSFCellStyle.BORDER_THIN);
        style2.setBorderTop(HSSFCellStyle.BORDER_THIN);
        style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        // 生成另一个字体
        HSSFFont font2 = workbook.createFont();
        font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
        // 把字体应用到当前的样式
        style2.setFont(font2);

        // 声明一个画图的顶级管理器
        HSSFPatriarch drawing = sheet.createDrawingPatriarch();
        HSSFClientAnchor anchor = drawing.createAnchor(0,0,0,0,9,0,11,6);

        // 产生表格标题并加中文批注
        //HSSFRow row = sheet.createRow(0);
        //T t = dataset.get(0);
        //Field[] titles = t.getClass().getDeclaredFields();
        //for (short i = 0; i < titles.length; i++) {
        //    HSSFCell cell = row.createCell(i);
        //    //cell.setCellStyle(style2);
        //    Field field = titles[i];
        //    String fieldName = field.getName();
        //    //String getMethodName = "get"
        //    //        + fieldName.substring(0, 1).toUpperCase()
        //    //        + fieldName.substring(1);
        //    cell.setCellValue(fieldName);
        //    //添加中文标题
        //    //Drawing drawing = sheet.createDrawingPatriarch();
        //    HSSFComment comment = drawing.createCellComment(anchor);
        //
        //    RichTextString str0 = new HSSFRichTextString(comments[i]);
        //    comment.setString(str0);
        //    cell.setCellComment(comment);
        //}


        // 产生表格中文标题行
        HSSFRow row = sheet.createRow(0);
        for (short i = 0; i < comments.length; i++) {
            HSSFCell cell = row.createCell(i);
            cell.setCellValue(comments[i]);

        }

        // 产生表格英文标题行
        row = sheet.createRow(1);
        T t = dataset.get(0);
        Field[] titles = t.getClass().getDeclaredFields();
        for (short i = 0; i < titles.length; i++) {
            HSSFCell cell = row.createCell(i);
            Field field = titles[i];
            String fieldName = field.getName();
            cell.setCellValue(fieldName);
        }

        // 遍历集合数据，产生数据行
        Iterator<T> it = dataset.iterator();
        int index = 1;
        while (it.hasNext()) {
            index++;
            row = sheet.createRow(index);
            t = (T) it.next();
            // 利用反射，根据javabean属性的先后顺序，动态调用getXxx()方法得到属性值
            Field[] fields = t.getClass().getDeclaredFields();
            for (short i = 0; i < fields.length; i++) {
                HSSFCell cell = row.createCell(i);
                //cell.setCellStyle(style2);
                Field field = fields[i];
                String fieldName = field.getName();
                String getMethodName = "get"
                        + fieldName.substring(0, 1).toUpperCase()
                        + fieldName.substring(1);
                Class tCls = t.getClass();
                Method getMethod = tCls.getMethod(getMethodName,
                        new Class[]{});
                Object value = getMethod.invoke(t, new Object[]{});
                if (value != null) {
                    // 判断值的类型后进行强制类型转换
                    //Object textValue = null;
                    if (value instanceof Integer) {
                        int intValue = (Integer) value;
                        cell.setCellValue(intValue);
                    } else if (value instanceof Float) {
                        float fValue = (Float) value;
                        cell.setCellValue(fValue);
                    } else if (value instanceof Double) {
                        double dValue = (Double) value;
                        cell.setCellValue(dValue);
                    } else if (value instanceof Long) {
                        long longValue = (Long) value;
                        cell.setCellValue(longValue);
                    }
                    if (value instanceof Date) {
                        DateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        //cell.setCellValue((Date) value);
                        cell.setCellValue(formater.format(value));
                    } else {
                        // 其它数据类型都当作字符串简单处理
                        cell.setCellValue(value.toString());
                    }
                }
            }
        }
        return workbook;
    }

    /*
    导出流
     */
    public void exportExcelStream(ExcelExportUtil<T> util, String outputName, List<T> outDataSet, HttpServletResponse response) throws Exception {
        Workbook wb = null;
        wb = util.exportExcel(outputName, outDataSet,null);
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment;filename=" + outputName + ".xls");
        OutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            wb.write(outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void exportExcelStream(ExcelExportUtil<T> util, String outputName, List<T> outDataSet,String[] comments, HttpServletResponse response) throws Exception {
        Workbook wb;
        wb = util.exportExcel(outputName, outDataSet,comments);
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment;filename=" + outputName + ".xls");
        OutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            wb.write(outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //
    //
    //public static void main(String[] args) throws Exception {
    //
    //    // 测试学生
    //
    //    List<Student> dataset = new ArrayList<Student>();
    //    dataset.add(new Student(10000001, "a", 20, "0", new Date()));
    //    dataset.add(new Student(20000002, "b", 24, "0", null));
    //    dataset.add(new Student(30000003, "c", 22, "1", null
    //    ));
    //
    //    OutputStream out = new FileOutputStream("C:\\Users\\e20160504\\Desktop\\test1.xls");
    //
    //    ExcelExportUtil<Student> ex = new ExcelExportUtil<Student>();
    //    Workbook wb = ex.exportExcel("test", dataset);
    //    wb.write(out);
    //
    //    out.close();
    //    //JOptionPane.showMessageDialog(null, "导出成功!");
    //    System.out.println("excel导出成功！");
    //
    //}

}
